package com.blrs.service.process.impl;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.blrs.common.exception.ServiceException;
import com.blrs.common.utils.uuid.UUID;
import com.blrs.domain.ProcessStage;
import com.blrs.domain.QualificationInfo;
import com.blrs.domain.StageAchievement;
import com.blrs.domain.dto.AchievementDTO;
import com.blrs.domain.dto.ProcessStageDTO;
import com.blrs.domain.dto.ProcessTemplateDTO;
import com.blrs.mapper.ProcessStageMapper;
import com.blrs.mapper.QualificationInfoMapper;
import com.blrs.mapper.StageAchievementMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.blrs.mapper.ProcessTemplateMapper;
import com.blrs.domain.ProcessTemplate;
import com.blrs.service.process.IProcessTemplateService;
import com.blrs.common.utils.SecurityUtils;

@Service
public class ProcessTemplateServiceImpl implements IProcessTemplateService {
    @Autowired
    private ProcessTemplateMapper processTemplateMapper;

    @Autowired
    private ProcessStageMapper processStageMapper;

    @Autowired
    private StageAchievementMapper stageAchievementMapper;

    @Autowired
    private QualificationInfoMapper qualificationInfoMapper;

    @Override
    public ProcessTemplate selectProcessTemplateById(String id) {
        ProcessTemplate template = processTemplateMapper.selectProcessTemplateById(id);
        if (template != null) {
            // 查询关联的阶段信息
            List<ProcessStage> stages = processStageMapper.selectProcessStagesByTemplateId(id);
            for (ProcessStage stage : stages) {
                // 查询每个阶段的成果信息
                List<StageAchievement> achievements = stageAchievementMapper.selectStageAchievementsByStageId(id,stage.getId());
                stage.setAchievements(achievements);
            }
            template.setStages(stages);
        }
        return template;
    }

    @Override
    public List<ProcessTemplate> selectProcessTemplateList(ProcessTemplate processTemplate) {
        processTemplate.setBelongTo(SecurityUtils.getOrgId());
        return processTemplateMapper.selectProcessTemplateList(processTemplate);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertProcessTemplate(ProcessTemplateDTO templateDTO) {
//        // 检查产品是否已关联其他模板
//        String[] productIds = templateDTO.getProductIds().split(",");
//        for (String productId : productIds) {
//            if (processTemplateMapper.checkProductTemplateExists(productId,SecurityUtils.getOrgId()) > 0) {
//                QualificationInfo qualificationInfo = qualificationInfoMapper.selectQualificationInfoById(productId);
//                throw new ServiceException("产品:" + qualificationInfo.getProductName() + " 已关联其他模板，一个产品只能关联一个模板");
//            }
//        }
        // 检查模板名称是否重复
        ProcessTemplate tempCheck = new ProcessTemplate();
        tempCheck.setTemplateName(templateDTO.getTemplateName());
        tempCheck.setBelongTo(SecurityUtils.getOrgId());
        if (checkTemplateNameUnique(tempCheck) > 0) {
            throw new ServiceException("模板名称已存在");
        }
        // 1. 保存模板主表
        ProcessTemplate template = new ProcessTemplate();
        BeanUtils.copyProperties(templateDTO, template);
        template.setId(UUID.randomUUID().toString());
        template.setBelongTo(SecurityUtils.getOrgId());
        template.setDelFlag("0");
        template.setCreationId(SecurityUtils.getUserId());
        template.setCreationName(SecurityUtils.getUsername());
        template.setCreationTime(new Date());
        int rows = processTemplateMapper.insertProcessTemplate(template);
        // 2. 保存阶段信息
        if (templateDTO.getStages() != null && !templateDTO.getStages().isEmpty()) {
            for (ProcessStageDTO stageDTO : templateDTO.getStages()) {
                // 保存阶段信息
                ProcessStage stage = new ProcessStage();
                BeanUtils.copyProperties(stageDTO, stage);
                stage.setId(UUID.randomUUID().toString());
                stage.setStageId(stageDTO.getStageId());
                stage.setTemplateId(template.getId());
                stage.setCreationId(SecurityUtils.getUserId());
                stage.setCreationName(SecurityUtils.getUsername());
                stage.setCreationTime(new Date());

                // 设置位置信息
                if (stageDTO.getPosition() != null) {
                    stage.setPositionX(stageDTO.getPosition().getX());
                    stage.setPositionY(stageDTO.getPosition().getY());
                }
                processStageMapper.insertProcessStage(stage);
                // 保存阶段成果信息
                if (stageDTO.getAchievements() != null && !stageDTO.getAchievements().isEmpty()) {
                    // 为每个阶段创建一个Set用于检查重复名称
                    Set<String> achievementNames = new HashSet<>();
                    for (AchievementDTO achievementDTO : stageDTO.getAchievements()) {
                        // 检查数据库中是否存在重复名称
                        int count = stageAchievementMapper.checkStageAchievementNameUnique(
                                stage.getStageId(),    // 阶段ID
                                template.getId(),       // 模板ID
                                achievementDTO.getAchievementName(),  // 成果名称
                                null
                        );
                        if (count > 0) {
                            throw new ServiceException("成果名称已存在：" + achievementDTO.getAchievementName());
                        }
                        // 检查当前阶段内是否有重复
                        if (!achievementNames.add(achievementDTO.getAchievementName())) {
                            throw new ServiceException("当前阶段内存在重复的成果名称：" + achievementDTO.getAchievementName());
                        }
                        StageAchievement achievement = new StageAchievement();
                        BeanUtils.copyProperties(achievementDTO, achievement);
                        achievement.setId(UUID.randomUUID().toString());
                        achievement.setStageId(stage.getId());
                        achievement.setTemplateId(template.getId());
                        achievement.setIsRequired(achievementDTO.getIsRequired());
                        achievement.setCreationId(SecurityUtils.getUserId());
                        achievement.setCreationName(SecurityUtils.getUsername());
                        achievement.setCreationTime(new Date());
                        stageAchievementMapper.insertStageAchievement(achievement);
                    }
                }
            }
        }
        return rows;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateProcessTemplate(ProcessTemplateDTO templateDTO) {
        // 1. 更新模板主表
        ProcessTemplate template = new ProcessTemplate();
        BeanUtils.copyProperties(templateDTO, template);
        template.setUpdateId(SecurityUtils.getUserId());
        template.setUpdateName(SecurityUtils.getUsername());
        template.setUpdateTime(new Date());
        int rows = processTemplateMapper.updateProcessTemplate(template);

        // 2. 删除原有阶段及其成果
        List<ProcessStage> oldStages = processStageMapper.selectProcessStagesByTemplateId(template.getId());
        for (ProcessStage oldStage : oldStages) {
            stageAchievementMapper.deleteStageAchievementByStageIdAndTemplateId(oldStage.getId(), templateDTO.getId());
        }
        processStageMapper.deleteByTemplateId(template.getId());

        // 3. 保存新的阶段信息
        if (templateDTO.getStages() != null && !templateDTO.getStages().isEmpty()) {
            for (ProcessStageDTO stageDTO : templateDTO.getStages()) {
                // 保存阶段信息
                ProcessStage stage = new ProcessStage();
                BeanUtils.copyProperties(stageDTO, stage);
                stage.setId(UUID.randomUUID().toString());
                stage.setStageId(stageDTO.getStageId());
                stage.setTemplateId(template.getId());
                stage.setUpdateId(SecurityUtils.getUserId());
                stage.setUpdateName(SecurityUtils.getUsername());
                stage.setUpdateTime(new Date());

                if (stageDTO.getPosition() != null) {
                    stage.setPositionX(stageDTO.getPosition().getX());
                    stage.setPositionY(stageDTO.getPosition().getY());
                }

                processStageMapper.insertProcessStage(stage);

                // 保存阶段成果信息
                if (stageDTO.getAchievements() != null && !stageDTO.getAchievements().isEmpty()) {
                    // 在这里创建Set，为每个阶段单独使用一个新的Set
                    Set<String> achievementNames = new HashSet<>();
                    for (AchievementDTO achievementDTO : stageDTO.getAchievements()) {
                        // 检查名称是否重复
                        int count = stageAchievementMapper.checkStageAchievementNameUnique(
                                stage.getId(),
                                template.getId(),
                                achievementDTO.getAchievementName(),
                                null
                        );

                        if (count > 0) {
                            throw new ServiceException("成果名称已存在：" + achievementDTO.getAchievementName());
                        }
                        // 检查当前阶段内是否有重复
                        if (!achievementNames.add(achievementDTO.getAchievementName())) {
                            throw new ServiceException("当前阶段内存在重复的成果名称：" + achievementDTO.getAchievementName());
                        }
                        StageAchievement achievement = new StageAchievement();
                        BeanUtils.copyProperties(achievementDTO, achievement);
                        achievement.setId(UUID.randomUUID().toString());
                        achievement.setStageId(stage.getId());
                        achievement.setTemplateId(template.getId());
                        achievement.setIsRequired(achievementDTO.getIsRequired());
                        achievement.setCreationId(SecurityUtils.getUserId());
                        achievement.setCreationName(SecurityUtils.getUsername());
                        achievement.setCreationTime(new Date());
                        achievement.setUpdateId(SecurityUtils.getUserId());
                        achievement.setUpdateName(SecurityUtils.getUsername());
                        achievement.setUpdateTime(new Date());
                        stageAchievementMapper.insertStageAchievement(achievement);
                    }
                }
            }
        }
        return rows;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteProcessTemplateByIds(String[] ids) {
        // 删除关联的阶段和成果
        for (String id : ids) {
            processStageMapper.deleteProcessStageById(id);
        }
        return processTemplateMapper.deleteProcessTemplateByIds(ids);
    }


    @Override
    @Transactional
    public int deleteProcessTemplateById(String id) {
        return processTemplateMapper.deleteProcessTemplateById(id);
    }

    @Override
    public Integer checkTemplateNameUnique(ProcessTemplate template) {
        ProcessTemplate temp = new ProcessTemplate();
        temp.setTemplateName(template.getTemplateName());
        temp.setBelongTo(SecurityUtils.getOrgId());
        if (template.getId() != null) {
            temp.setId(template.getId());
        }
        Integer count = processTemplateMapper.checkTemplateNameUnique(temp);
        if (count > 0) {
            return count; // 模板名称已存在
        }
        return 0; // 模板名称可用
    }
} 